package com.nikmesoft.android.ebox.helpers;

import java.io.DataInputStream;
import java.io.InputStream;
import java.io.OutputStream;

public class FileEncrypter {
	private static final int ENCRYPT_DISTANCE = 1024 * 2;

	public static void encrypt(String key, int length, InputStream fis,
			OutputStream fos) throws Throwable {

		DataInputStream dataInputStream = new DataInputStream(fis);
		byte[] bytes = new byte[length];
		dataInputStream.readFully(bytes);
		byte[] encodedKey = key.getBytes();
		for (int i = 0; i < bytes.length; i += ENCRYPT_DISTANCE) {
			bytes[i] = (byte) (bytes[i] ^ encodedKey[i % encodedKey.length]);
		}

		fos.write(bytes);
		fos.flush();
		fos.close();

	}

	public static void decrypt(String key,int length, InputStream fis, OutputStream fos)
			throws Throwable {
		DataInputStream dataInputStream = new DataInputStream(fis);
		byte[] bytes = new byte[length];
		dataInputStream.readFully(bytes);
		byte[] encodedKey = key.getBytes();
		for (int i = 0; i < bytes.length; i += ENCRYPT_DISTANCE) {
			bytes[i] = (byte) (bytes[i] ^ encodedKey[i % encodedKey.length]);
		}
		fos.write(bytes);
		fos.flush();
		fos.close();
	}

}
